var year = new Date().getFullYear();
var month = new Date().getMonth();
var day = new Date().getDate();

   
$(document).ready(function() { 

	var $calendar = $('#calendar');
	$calendar.weekCalendar({
		timeslotsPerHour: 4,

		height: function($calendar){
			return $(window).height() - $('#head').innerHeight() - 70;
		},

		businessHours : {
			start: 8,
			end: 18,
			limitDisplay: false
		}, 

		eventRender : function(calEvent, $event) {
			if(calEvent.end.getTime() < new Date().getTime()) {
				$event.css("backgroundColor", "#aaa");
				$event.find(".time").css({"backgroundColor": "#999", "border":"1px solid #888"});
			}
		},

		timeslotHeight: '10',

		// Text to use for display in navigation button
		buttonText: {
			today : "Dzisiaj",
			lastWeek: "Poprzedni tydzień",
			nextWeek : "Następny tydzień"
		},

		// A format to use for times displayed by the calendar
		timeFormat : "H:i",

		// A format to use for dates displayed in the calendar.
		dateFormat : "d F",

		// Renders timeslots in 24 hour time
		use24Hour : true,

		// Whether to use short day names for display in day column headers. Ie. ‘Sun’ instead of ‘Sunday’.
		useShortDayNames : false,

		// Determines what day of the week to start on. 0 = sunday, 1 = tuesday etc.
		firstDayOfWeek : 1,

		newEventText: "Termin zajęty",

		// Months of the year in short format.
		shortMonths : ["Sty", "Lut", "Mar", "Kwi", "Maj", "Cze", "Lip", "Sie", "Wrz", "Paź", "Lis", "Gru"],

		// Months of the year in long format.
		longMonths : ["Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec", "Sierpień", "Wrzesień", "Październik", "Listgopad", "Grudzień"],

		// Days of the week in short format
		shortDays : ["Nd", "Pn", "Wt", "Śr", "Czw", "Pt", "So"],

		// Days of the week in long format
		longDays : ["Niedziela", "Pniedziałek","Wtorek", "Środa", "Czwartek", "Piątek", "Sobota"], 

//			noEvents: function(){
//				
//			},

		eventNew : function(calEvent, $event) {
	         var $dialogContent = $("#event_edit_container");
	         resetForm($dialogContent);
	         var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
	         var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
	         var titleField = $dialogContent.find("input[name='title']");
	         var bodyField = $dialogContent.find("textarea[name='body']");
	
	         $dialogContent.dialog({
	            modal: true,
	            resizable:false,
	            width:340,
	            close: function() {
	               $dialogContent.dialog("destroy");
	               $dialogContent.hide();
	               $('#calendar').weekCalendar("removeUnsavedEvents");
	            },
	            buttons: {
	               "Dodaj" : function() {
	                  //calEvent.id = id;
	                  //id++;
	                  calEvent.start = new Date(startField.val());
	                  calEvent.end = new Date(endField.val());
	                  calEvent.title = titleField.val();
	                  calEvent.body = bodyField.val();
	
	                  $calendar.weekCalendar("removeUnsavedEvents");
	                  $calendar.weekCalendar("updateEvent", calEvent);
	                  $dialogContent.dialog("close");
	               },
	               "Anuluj" : function() {
	                  $dialogContent.dialog("close");
	               }
	            }
	         }).show();
	
	         $dialogContent.find(".date_holder").text($calendar.weekCalendar("formatDate", calEvent.start));
	         setupStartAndEndTimeFields(startField, endField, calEvent, $calendar.weekCalendar("getTimeslotTimes", calEvent.start));
	
	      },

		eventDrop : function(calEvent, $event) {
			displayMessage("<strong>Moved Event</strong><br/>Start: " + calEvent.start + "<br/>End: " + calEvent.end);
		},
		eventResize : function(calEvent, $event) {
			displayMessage("<strong>Resized Event</strong><br/>Start: " + calEvent.start + "<br/>End: " + calEvent.end);
		},
		eventClick : function(calEvent, $event) {
			displayMessage("<strong>Clicked Event</strong><br/>Start: " + calEvent.start + "<br/>End: " + calEvent.end);
		},
		eventMouseover : function(calEvent, $event) {
			displayMessage("<strong>Mouseover Event</strong><br/>Start: " + calEvent.start + "<br/>End: " + calEvent.end);
		},
		eventMouseout : function(calEvent, $event) {
			displayMessage("<strong>Mouseout Event</strong><br/>Start: " + calEvent.start + "<br/>End: " + calEvent.end);
		},
		noEvents : function() {
			displayMessage("There are no events for this week");
		},
		
		data: 
//				[
//					{
//						"id":1123123,
//						//"schedule_id":"1",
//						//"user_id":"1",
//						"start":"2010-03-12T12:15:00+01:00",
//						"end":"2010-03-12T13:15:00+01:00",
//						"title":"Tytu\u0142 wydarzenia Promotor"
//					},
//					{
//						"id":2123123,
//						//"schedule_id":"1",
//						//"user_id":"1",
//						"start":"2010-03-11T12:15:00+01:00",
//						"end":"2010-03-11T13:15:00+01:00",
//						"title":"Lalalla"
//					},
//					{
//						"id":10182,
//					    "start":"2010-03-13T12:15:00+01:00",
//					    "end":"2010-03-13T13:15:00.000+00:00",
//					    "title":"Lunch with Mike"
//					},
//					{
//						"id":10182,
//						"start":"2010-03-13T14:00:00.000+01:00",
//						"end":"2010-03-13T15:00:00.000+01:00",
//						"title":"Dev Meeting"
//				    }
//										]
			function(start, end, callback) {
				$.ajax({
					url: '/schedule/index/events/schedule/promotor',
					dataType:'json',
					success: function(data, textStatus, XMLHttpRequest) {
						if (data.status == 'SUCCESS')
						{
							callback(data.result);
							console.log(callback);
							console.log(data.result);

							$.jGrowl('Wydarzenia zostały pobrane');
						}

						$.each(data.messages, function(message){
							$.jGrowl(message);
						});
					},
					error: function(XMLHttpRequest, textStatus, errorThrown) {
						$.jGrowl('Wystąpił błąd podczas pobierania wydarzeń: ' + textStatus,  { life: 5000 });
					}
				});
			}
	});


	/*
	    * Sets up the start and end time fields in the calendar event
	    * form for editing based on the calendar event being edited
	    */
	   function setupStartAndEndTimeFields($startTimeField, $endTimeField, calEvent, timeslotTimes) {

	      for (var i = 0; i < timeslotTimes.length; i++) {
	         var startTime = timeslotTimes[i].start;
	         var endTime = timeslotTimes[i].end;
	         var startSelected = "";
	         if (startTime.getTime() === calEvent.start.getTime()) {
	            startSelected = "selected=\"selected\"";
	         }
	         var endSelected = "";
	         if (endTime.getTime() === calEvent.end.getTime()) {
	            endSelected = "selected=\"selected\"";
	         }
	         $startTimeField.append("<option value=\"" + startTime + "\" " + startSelected + ">" + timeslotTimes[i].startFormatted + "</option>");
	         $endTimeField.append("<option value=\"" + endTime + "\" " + endSelected + ">" + timeslotTimes[i].endFormatted + "</option>");

	      }
	      $endTimeOptions = $endTimeField.find("option");
	      $startTimeField.trigger("change");
	   }

	   var $endTimeField = $("select[name='end']");
	   var $endTimeOptions = $endTimeField.find("option");

	   //reduces the end time options to be only after the start time options.
	   $("select[name='start']").change(function() {
	      var startTime = $(this).find(":selected").val();
	      var currentEndTime = $endTimeField.find("option:selected").val();
	      $endTimeField.html(
	            $endTimeOptions.filter(function() {
	               return startTime < $(this).val();
	            })
	            );

	      var endTimeSelected = false;
	      $endTimeField.find("option").each(function() {
	         if ($(this).val() === currentEndTime) {
	            $(this).attr("selected", "selected");
	            endTimeSelected = true;
	            return false;
	         }
	      });

	      if (!endTimeSelected) {
	         //automatically select an end date 2 slots away.
	         $endTimeField.find("option:eq(1)").attr("selected", "selected");
	      }

	   });
			

	function resetForm($dialogContent) {
      $dialogContent.find("input").val("");
      $dialogContent.find("textarea").val("");
   }

			
	
	function actionLoop()
	{
	}

	function addAction() {
	}
	
	function displayMessage(message) {
		$.jGrowl(message,  { life: 5000 });
	}

	/**
	 * Opcje po zalogowaniu
	 */

	// edytowalne elementy
	$('.editable').editable('save',{
		indicator : 'Zapisywanie...',
        tooltip   : 'Naciśnij by edytować...',
        //type      : 'textarea',
		cancel    : 'Cancel',
		submit    : 'Zapisz',
		cssclass : 'someclass'
	});
	$('.editable_textarea').editable('save',{
		indicator : 'Zapisywanie...',
        tooltip   : 'Naciśnij by edytować...',
        type      : 'textarea',
		cancel    : 'Cancel',
		submit    : 'Zapisz',
		cssclass : 'editable_textarea'
	});

	$('.filtrowanie_info > select').change(function(){
		window.location.href = window.location.href.replace(/\?username=\d+/,'') + '?username=' + this.value;
	});
	
	/*
	$.ajaxStart(function(){
		$.jGrowl('Pobieranie wydarzeń',  { life: 5000 });
	});
	$.ajaxStop(function(){
		$.jGrowl('Wydarzenia zostały pobrane',  { life: 5000 });
	});
	*/
	
	
});